package com.kanshu.ksgb.fastread.doudou.module.book.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewStub;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.dl7.recycler.helper.RecyclerViewHelper;
import com.kanshu.ksgb.fastread.doudou.R;
import com.kanshu.ksgb.fastread.doudou.app.constants.ARouterConfig;
import com.kanshu.ksgb.fastread.doudou.app.constants.Constants;
import com.kanshu.ksgb.fastread.doudou.common.business.utils.ReaderJumpConfig;
import com.kanshu.ksgb.fastread.doudou.base.basemvp.IGenrialMvpView;
import com.kanshu.ksgb.fastread.doudou.base.baseui.BaseActivity;
import com.kanshu.ksgb.fastread.doudou.common.net.bean.BaseResult;
import com.kanshu.ksgb.fastread.doudou.common.util.SwipeRefreshHelper;
import com.kanshu.ksgb.fastread.doudou.common.util.ToastUtil;
import com.kanshu.ksgb.fastread.doudou.common.util.Utils;
import com.kanshu.ksgb.fastread.doudou.common.view.EmptyLayout;
import com.kanshu.ksgb.fastread.doudou.module.book.adapter.ChapterListAdapter;
import com.kanshu.ksgb.fastread.doudou.module.book.bean.ChapterBean;
import com.kanshu.ksgb.fastread.doudou.common.business.commonbean.ReaderInputParams;
import com.kanshu.ksgb.fastread.doudou.common.business.event.ReaderFinishEvent;
import com.kanshu.ksgb.fastread.doudou.module.book.presenter.BookPresenter;
import com.kanshu.ksgb.fastread.doudou.module.book.retrofit.requestparams.BookPageParams;
import com.kanshu.ksgb.fastread.doudou.common.business.pay.event.PayActionEvent;
import com.kanshu.ksgb.fastread.doudou.module.reader.view.BookReadErrorLayout;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by wcy on 2017\7\4
 */
@Route(path = ARouterConfig.BOOK_CHAPTER_LIST)
public class ChapterListActivity extends BaseActivity implements IGenrialMvpView<BaseResult<List<ChapterBean>>>, SwipeRefreshLayout.OnRefreshListener {
    public static final String EXTRA_BOOK_ID = "book_id";
    public static final String EXTRA_BOOK_CHAPTER = "book_chapter";
    @BindView(R.id.recyler_view)
    RecyclerView mRecylerView;
    @BindView(R.id.empty_layout)
    EmptyLayout mEmptyLayout;
    String mBookId;
    List<ChapterBean> mList = new ArrayList<>();
    ChapterListAdapter mAdapter;
    BookPageParams mRequestParams = new BookPageParams();
    BookPresenter mPresenter = new BookPresenter(lifeCyclerSubject);
    @BindView(R.id.order_by)
    TextView mOrderBy;
    boolean mIsAsc;
    @BindView(R.id.swipe_refresh)
    TwinklingRefreshLayout mSwipeRefresh;
    @BindView(R.id.scroll_to_top)
    View mScrollToTop;
    /****
     * if chapter >=0 , it must from book reader, we replace pull refresh func to load pre page
     */
    int chapter = -1;
    public static final int PAGE_SIZE = 30;
    private int prePageMin = -1;
    private int prePageMax = -1;
    private String mOldOrder;
    private String mCurrentOrder;
    // 错误处理页面
    private BookReadErrorLayout mErrorLayout;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chapterlist_layout);
        ButterKnife.bind(this);
        parseIntent();
        init();
    }

    @OnClick({R.id.order_by,R.id.scroll_to_top})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.order_by:
                mOrderBy.setEnabled(false);
                mScrollToTop.setEnabled(false);
                mList.clear();
                mAdapter.notifyDataSetChanged();
                handleOrderBy();
                break;
            case R.id.scroll_to_top:
                if (prePageMin == 1) {
                    mRecylerView.scrollToPosition(0);
                } else {
                    mOrderBy.setEnabled(false);
                    mScrollToTop.setEnabled(false);
                    mList.clear();
                    mAdapter.notifyDataSetChanged();

                    //获取第一页的数据
                    mRequestParams.page =1;
                    mRequestParams.num = 100;
                    prePageMax =mRequestParams.page;
                    prePageMin =mRequestParams.page;
                    showLoading(null);
                    mPresenter.getChapterList(mRequestParams);
                }
                //mScrollToTop.setEnabled(false);

                break;
            default:
                break;
        }
    }

    private int initPage = 0;
    /**
     * 处理排序
     */
    private void handleOrderBy() {
        mRequestParams.book_id = mBookId;
        mAdapter.setIsNoMoreData(false);
        if (chapter >= 0) {
            int page = chapter / PAGE_SIZE + ((chapter % PAGE_SIZE == 0) ? 0 : 1);
            mRequestParams.page = page;
            prePageMax = page;
            prePageMin = page;
            mRequestParams.num = PAGE_SIZE;
        } else {
            mRequestParams.page = 1;
            prePageMax = mRequestParams.page;
            prePageMin = mRequestParams.page;
            mRequestParams.num = 100;
        }
        if (mIsAsc) {
            mRequestParams.order_by = BookPageParams.ORDER_DESC;
            mRequestParams.page = 1;
            mRequestParams.num = 100;
            prePageMax =mRequestParams.page;
            prePageMin =mRequestParams.page;
        } else {
            mRequestParams.order_by = BookPageParams.ORDER_ASC;
        }
        showLoading(null);
        initPage = mRequestParams.page;
        mPresenter.getChapterList(mRequestParams);
    }

    private void parseIntent() {
        mBookId = getIntent().getStringExtra(EXTRA_BOOK_ID);
        chapter = getIntent().getIntExtra(EXTRA_BOOK_CHAPTER, -1);

    }

    private void init() {
        setTitle("目录");
        SwipeRefreshHelper.init(mSwipeRefresh, this);
        mOrderBy.setEnabled(false);
        mScrollToTop.setEnabled(false);
        mPresenter.setChapterListView(this);
        mAdapter = new ChapterListAdapter(this, mList, mBookId);
        mEmptyLayout.setRetryListener(this::handleOrderBy);
        RecyclerViewHelper.initRecyclerViewV(this, mRecylerView, false, mAdapter);
        mAdapter.setRequestDataListener(() -> {
            mOrderBy.setEnabled(false);
            mScrollToTop.setEnabled(false);
            if (chapter >= 0) {
                prePageMax++;
                mRequestParams.page = prePageMax;
            } else {
                mRequestParams.page++;
            }
            mPresenter.getChapterList(mRequestParams);
        });
        handleOrderBy();
        mAdapter.setOnItemClickListener((view, position) -> {
            if (position >= mList.size()) {
                return;
            }
            ChapterBean chapterBean = mList.get(position - mAdapter.getHeaderViewsCount());
            String chapter_id = chapterBean.content_id;
            String book_id = chapterBean.book_id;
            String order = chapterBean.order;
            ReaderInputParams params = new ReaderInputParams();
            params.book_id = book_id;
            params.content_id = chapter_id;
            params.order = order;
            ReaderJumpConfig.startReaderActivity(ChapterListActivity.this, params);
        });
        EventBus.getDefault().register(this);


        mRecylerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
                //显示第一个分页，第一个章节名的时候 不显示置顶按钮。
                if (prePageMin == 1&&manager.findFirstVisibleItemPosition()==0) {
                    mScrollToTop.setVisibility(View.INVISIBLE);
                }else {
                    mScrollToTop.setVisibility(View.VISIBLE);
                }
            }
        });


    }

    private boolean addLast(BaseResult<List<ChapterBean>> chapterBeen) {
        if (mList.size() == 0) {
            return true;
        }
        if (chapterBeen == null || chapterBeen.result == null || chapterBeen.result.data == null) {
            return true;
        }
        if (chapterBeen.result.data.size() == 0) {
            return true;
        }

        ChapterBean preFisrt = mList.get(0);
        int loadSize = chapterBeen.result.data.size();
        ChapterBean lastLoad = chapterBeen.result.data.get(loadSize - 1);
        int preOrder = Integer.valueOf(preFisrt.order);
        int lastLoadOrder = Integer.valueOf(lastLoad.order);
        if (TextUtils.equals(mRequestParams.order_by, BookPageParams.ORDER_ASC)) {
            return lastLoadOrder >= preOrder;
        } else {
            return lastLoadOrder < preOrder;
        }
    }


    @Override
    public void showContent(BaseResult<List<ChapterBean>> chapterBeen) {
        int page = mRequestParams.page;
        if (chapter < 0) {
            if (mRequestParams.page == 1) {
                if (Utils.isEmptyList(chapterBeen.result.data) && mList.size() <= 0) {
                    //mEmptyLayout.setEmptyMessage("暂无记录");
                    mEmptyLayout.setEmptyStatus(EmptyLayout.STATUS_NO_DATA);
                    return;
                }
                mList.clear();
                mAdapter.setIsNoMoreData(false);
            }
        }
        if (mEmptyLayout != null) {
            mEmptyLayout.hide();
        }
        SwipeRefreshHelper.swipeRefreshCompleted(mSwipeRefresh, mAdapter);
        if (mRequestParams.page >= chapterBeen.result.total_page) {
            mAdapter.noMoreData();
        }
        mOldOrder = mCurrentOrder;
        mCurrentOrder = BookPageParams.ORDER_ASC;
        if(!TextUtils.equals(mOldOrder, mCurrentOrder)){
            mList.clear();
        }
        boolean addLast = addLast(chapterBeen);
        int lastVisibleItem = 0;
        LinearLayoutManager layoutManager = (LinearLayoutManager) mRecylerView.getLayoutManager();
        lastVisibleItem = layoutManager.findLastVisibleItemPosition();
        if (addLast) {
            mList.addAll(chapterBeen.result.data);
        } else {
            mList.addAll(0, chapterBeen.result.data);
        }
        mAdapter.notifyDataSetChanged();
        if(mRequestParams.page == initPage){//首次加载，就直接将当前章节显示在首部
            int visibleCount = lastVisibleItem - layoutManager.findFirstVisibleItemPosition();
            int  currentPosition = mAdapter.getReadPosition();
            int index = currentPosition - visibleCount;
            if(index<0){
                index = 0;
            }
            layoutManager.scrollToPosition(index);

        }else {
            if (!addLast && mIsAsc) {
                mRecylerView.scrollToPosition(lastVisibleItem + 98);
            } else {
                if (page == 1) {
                    mRecylerView.scrollToPosition(0);
                }
            }

        }
        if (mRequestParams.order_by.equals(BookPageParams.ORDER_ASC)) {
            mOrderBy.setText("正序");
            mIsAsc = true;
            mOrderBy.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.ic_asc, 0, 0, 0);
        } else {
            mIsAsc = false;
            mOrderBy.setText("倒序");
            mOrderBy.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.ic_desc, 0, 0, 0);
        }
        mOrderBy.setEnabled(true);
        mScrollToTop.setEnabled(true);
    }

    @Override
    public void showError(int errCode, String errDesc) {
        if (errCode == Constants.ErrCode.Offline) {
            if (mEmptyLayout != null) {
                mEmptyLayout.hide();
            }
            handleBookError(errCode);
            return;
        }
        ToastUtil.showStaticMessage(getString(R.string.standard_net_tip));
        if (Utils.isEmptyList(mList)) {
            if (errCode == Constants.ErrCode.NoData) {
                mEmptyLayout.setEmptyStatus(EmptyLayout.STATUS_NO_DATA);
            } else {
                mEmptyLayout.setEmptyStatus(EmptyLayout.STATUS_NO_NET);
            }
        }
        mOrderBy.setEnabled(true);
        mScrollToTop.setEnabled(true);
    }

    @Override
    public void showLoading(String s) {
        mEmptyLayout.setEmptyStatus(EmptyLayout.STATUS_LOADING);
    }

    @Override
    public void dismissLoading() {
        if (mEmptyLayout != null) {
            mEmptyLayout.hide();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPresenter.detachView();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handlePayActionEvent(PayActionEvent event) {
        if (!event.isSuccess) {
            if (event.errCode == PayActionEvent.FINISH_PAGE) {
                finish();
            }
        }
    }


    public static void actionStart(Context context, String book_id, int chapter) {
        Intent intent = new Intent(context, ChapterListActivity.class);
        intent.putExtra(EXTRA_BOOK_ID, book_id);
        intent.putExtra(EXTRA_BOOK_CHAPTER, chapter);
        context.startActivity(intent);
    }

    @Override
    public void onRefresh() {
        if (chapter >= 0) {
            if (prePageMin > 1) {
                prePageMin--;
                mRequestParams.page = prePageMin;
            } else {
                mSwipeRefresh.finishRefreshing();
                return;
            }
        } else {
            mRequestParams.page = 1;
        }
        mPresenter.getChapterList(mRequestParams);
        mOrderBy.setEnabled(false);
        mScrollToTop.setEnabled(false);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(getClass().getSimpleName());
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(getClass().getSimpleName());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleFinishEvent(ReaderFinishEvent event) {
//        mRequestParams.page = 1;
//        showLoading(null);
//        mPresenter.getChapterList(mRequestParams);
//        mOrderBy.setEnabled(false);
        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 根据错误码处理阅读器页面
     *
     * @param code
     */
    private void handleBookError(int code) {
        if (mErrorLayout == null) {
            ViewStub stub = findViewById(R.id.err_stub);
            if (stub != null) {
                View v = stub.inflate();
                mErrorLayout = v.findViewById(R.id.err_handle_container);
            }
        }
        if (mErrorLayout != null) {
            mErrorLayout.setCallback(new BookReadErrorLayout.ReadErrCallback() {
                @Override
                public void onRetry() {
                }
                @Override
                public void onTouch() {
                }
            });
            mErrorLayout.refreshByErrorCode(code);
        }
    }

}
